const { query } = require('../config/database');

class DriftBottle {
  /**
   * 创建漂流瓶
   * @param {string} userId - 发送者用户ID
   * @param {string} content - 漂流瓶内容
   * @returns {Object} 创建的漂流瓶信息
   */
  static async create(userId, content) {
    try {
      // 参数验证
      if (!content || content.trim().length === 0) {
        throw new Error('漂流瓶内容不能为空');
      }
      
      if (content.length > 500) {
        throw new Error('漂流瓶内容不能超过500个字符');
      }

      const sql = `
        INSERT INTO drift_bottles (user_id, content)
        VALUES (?, ?)
      `;
      
      const result = await query(sql, [userId, content.trim()]);
      
      // 返回创建的漂流瓶信息
      return {
        id: result.insertId,
        userId,
        content: content.trim(),
        pickCount: 0,
        status: 1,
        createdAt: new Date()
      };
    } catch (error) {
      console.error('创建漂流瓶失败:', error);
      throw error;
    }
  }

  /**
   * 随机捡起一个漂流瓶
   * @param {string} pickerId - 捡起者用户ID
   * @returns {Object|null} 漂流瓶信息或null
   */
  static async pickRandom(pickerId) {
    try {
      // 查找可捡起的漂流瓶（排除自己发送的和已经捡起过的）
      const sql = `
        SELECT 
          db.id,
          db.user_id as userId,
          db.content,
          db.pick_count as pickCount,
          db.created_at as createdAt,
          u.nick_name as senderNickName,
          u.avatar as senderAvatar,
          u.email as senderEmail
        FROM drift_bottles db
        LEFT JOIN users u ON db.user_id = u.user_id
        WHERE db.status = 1 
          AND db.user_id != ?
          AND db.id NOT IN (
            SELECT bottle_id 
            FROM drift_bottle_picks 
            WHERE picker_id = ?
          )
        ORDER BY RAND()
        LIMIT 1
      `;
      
      const bottles = await query(sql, [pickerId, pickerId]);
      
      if (bottles.length === 0) {
        return null; // 没有可捡起的漂流瓶
      }
      
      const bottle = bottles[0];
      
      // 记录捡起行为
      const pickSql = `
        INSERT INTO drift_bottle_picks (bottle_id, picker_id)
        VALUES (?, ?)
      `;
      
      await query(pickSql, [bottle.id, pickerId]);
      
      // 更新漂流瓶的捡起次数
      const updateSql = `
        UPDATE drift_bottles 
        SET pick_count = pick_count + 1, updated_at = CURRENT_TIMESTAMP
        WHERE id = ?
      `;
      
      await query(updateSql, [bottle.id]);
      
      // 返回漂流瓶信息（包含更新后的捡起次数）
      return {
        id: bottle.id,
        content: bottle.content,
        pickCount: bottle.pickCount + 1,
        createdAt: bottle.createdAt,
        sender: {
          userId: bottle.userId,
          nickName: bottle.senderNickName,
          avatar: bottle.senderAvatar,
          email: bottle.senderEmail
        }
      };
    } catch (error) {
      console.error('捡起漂流瓶失败:', error);
      throw error;
    }
  }

  /**
   * 获取用户发送的漂流瓶列表（可选功能）
   * @param {string} userId - 用户ID
   * @param {number} page - 页码
   * @param {number} limit - 每页数量
   * @returns {Object} 漂流瓶列表和分页信息
   */
  static async getUserSentBottles(userId, page = 1, limit = 10) {
    try {
      const offset = (page - 1) * limit;
      
      // 获取总数
      const countSql = `
        SELECT COUNT(*) as total
        FROM drift_bottles
        WHERE user_id = ? AND status = 1
      `;
      
      const countResult = await query(countSql, [userId]);
      const total = countResult[0].total;
      
      // 获取漂流瓶列表
      const sql = `
        SELECT 
          id,
          content,
          pick_count as pickCount,
          created_at as createdAt
        FROM drift_bottles
        WHERE user_id = ? AND status = 1
        ORDER BY created_at DESC
        LIMIT ? OFFSET ?
      `;
      
      const bottles = await query(sql, [userId, limit, offset]);
      
      return {
        bottles,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit)
        }
      };
    } catch (error) {
      console.error('获取用户漂流瓶列表失败:', error);
      throw error;
    }
  }

  /**
   * 获取用户捡起的漂流瓶列表（可选功能）
   * @param {string} userId - 用户ID
   * @param {number} page - 页码
   * @param {number} limit - 每页数量
   * @returns {Object} 漂流瓶列表和分页信息
   */
  static async getUserPickedBottles(userId, page = 1, limit = 10) {
    try {
      const offset = (page - 1) * limit;
      
      // 获取总数
      const countSql = `
        SELECT COUNT(*) as total
        FROM drift_bottle_picks dbp
        LEFT JOIN drift_bottles db ON dbp.bottle_id = db.id
        WHERE dbp.picker_id = ? AND db.status = 1
      `;
      
      const countResult = await query(countSql, [userId]);
      const total = countResult[0].total;
      
      // 获取漂流瓶列表
      const sql = `
        SELECT 
          db.id,
          db.content,
          db.pick_count as pickCount,
          db.created_at as createdAt,
          dbp.picked_at as pickedAt,
          u.nick_name as senderNickName,
          u.avatar as senderAvatar
        FROM drift_bottle_picks dbp
        LEFT JOIN drift_bottles db ON dbp.bottle_id = db.id
        LEFT JOIN users u ON db.user_id = u.user_id
        WHERE dbp.picker_id = ? AND db.status = 1
        ORDER BY dbp.picked_at DESC
        LIMIT ? OFFSET ?
      `;
      
      const result = await query(sql, [userId, limit, offset]);
      
      const bottles = result.map(row => ({
        id: row.id,
        content: row.content,
        pickCount: row.pickCount,
        createdAt: row.createdAt,
        pickedAt: row.pickedAt,
        sender: {
          nickName: row.senderNickName,
          avatar: row.senderAvatar
        }
      }));
      
      return {
        bottles,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit)
        }
      };
    } catch (error) {
      console.error('获取用户捡起的漂流瓶列表失败:', error);
      throw error;
    }
  }
}

module.exports = DriftBottle;